import easemob from 'easemob-websdk'

class EasemobIM {
  constructor (options) {
    this.conn = null
    this.username = options.username
    this.password = options.password
    this.appKey = options.appKey
    this.onReceiveMsg = options.onReceiveMsg
    this.onSendMsgSuccess = options.onSendMsgSuccess
    this.onSendMsgError = options.onSendMsgError
  }

  // 初始化环信IM
  init () {
    this.conn = new easemob.connection({
      appKey: this.appKey,
      isHttpDNS: false,
      isMultiLoginSessions: false,
      https: false,
      url: 'im-api.easemob.com',
      apiUrl: 'https://a1.easemob.com'
    })

    this.conn.listen({
      onOpened: (message) => {
        console.log('连接成功', message)
      },
      onClosed: (message) => {
        console.warn('连接已关闭', message)
      },
      onTextMessage: (message) => {
        console.log('收到消息', message)
        this.onReceiveMsg && this.onReceiveMsg(message)
      }
    })
  }

  // 连接环信IM
  connect () {
    return new Promise((resolve, reject) => {
      this.conn.open({
        apiUrl: 'https://a1.easemob.com',
        user: this.username,
        pwd: this.password,
        appKey: this.appKey,
        success: () => {
          console.log('连接成功')
          resolve()
        },
        error: (error) => {
          console.error('连接失败', error)
          reject(error)
        }
      })
    })
  }

  // 发送文本消息
  sendTextMessage (to, text) {
    const id = this.conn.getUniqueId()
	// 创建文本消息对象
    const  msg= new easemob.EMMessage.createTxtSendMessage(to, id)
   console.log("msg",msg)
   return false;
	msg.set({
      to,
      msg: text,
      success: () => {
        console.log('发送成功')
        this.onSendMsgSuccess && this.onSendMsgSuccess(msg)
      },
      error: (error) => {
        console.error('发送失败', error)
        this.onSendMsgError && this.onSendMsgError(error)
      }
    })
    this.conn.send(msg.body)
  }

  // 断开连接
  disconnect () {
    this.conn.close()
  }
}

export default EasemobIM
